package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.constants.RocketMQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.TbUser;
import com.leyou.user.mapper.TbUserMapper;
import com.leyou.user.service.TbUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.RocketMQConstants.TAGS.VERIFY_CODE_TAGS;
import static com.leyou.common.constants.RocketMQConstants.TOPIC.SMS_TOPIC_NAME;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2020-10-07
 */
@Slf4j
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    /**
     * 校验数据是否可用
     * @param data
     * @param type 1，用户名；2，手机
     * @return  true 数据可用,数据库没有  false 数据不可用，数据库有
     */
    @Override
    public Boolean checkUserData(String data, Integer type) {

//        构造查询条件
        QueryWrapper<TbUser> queryWrapper =  new QueryWrapper<>();

        switch (type) {
            case 1:
                queryWrapper.lambda().eq(TbUser::getUsername,data);
                break;
            case 2:
                queryWrapper.lambda().eq(TbUser::getPhone,data);
                break;
            default:
                throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

//        查询数据
        int count = this.count(queryWrapper);
        return count==0;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

//    redisKey的前缀
    String PRE_FIX = "ly:user:verify:phone:";
    /**
     * 发送验证码
     * 需要发送RocketMQ消息，内容包括手机号，验证码
     * 验证码 随机生成 4 -6 数字
     * 需要把验证码存入redis中 ，使用string类型，key - phone val-code ex有效期
     * @param phone
     * @return
     */
    @Override
    public void sendCode(String phone) {
//         验证手机号码格式
        if(StringUtils.isBlank(phone) || !RegexUtils.isPhone(phone)){
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
//     判断手机号是否已经使用
        if(!this.checkUserData(phone,2)){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
//        生成随机验证码
        String code = RandomStringUtils.randomNumeric(4);
        log.info("code =={}",code);
//        redis 的key值
        String redisKey = PRE_FIX + phone;
//        把code放入redis中
        redisTemplate.opsForValue().set(redisKey,code,3, TimeUnit.MINUTES);
        String dest = SMS_TOPIC_NAME +":"+ VERIFY_CODE_TAGS;
        Map<String,String> map = new HashMap<>();
        map.put("phone",phone);
        map.put("code",code);
        String payload = JsonUtils.toString(map);
        log.info("发送消息内容，msg={}",payload);
//        发送RocketMQ消息
        rocketMQTemplate.convertAndSend(dest,payload);

    }

    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * 用户注册
     *
     * @param tbUser
     * @param code
     * @return
     */
    @Override
    public void register(TbUser tbUser,String code) {
//        验证数据
        if(tbUser == null){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        if(StringUtils.isBlank(tbUser.getUsername()) ||
                StringUtils.isBlank(tbUser.getPhone())){
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
//        获取redis中的验证码
        String redisKey = PRE_FIX + tbUser.getPhone();
        String cacheCode = redisTemplate.opsForValue().get(redisKey);
//        验证短信验证码
        if(!StringUtils.equals(code,cacheCode)){
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }
//        以前 MD5（raw+salt）* N
//        把密码加密，bcryptPasswordencode方式，salt是随机的
        String encodePwd = encoder.encode(tbUser.getPassword());
        tbUser.setPassword(encodePwd);
//        保存数据
        boolean b = this.save(tbUser);
        if(!b){
           throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }
    /**
     * 根据用户名和密码查询用户信息
     * @param userName
     * @param passWord
     * @return
     */
    @Override
    public UserDTO queryUser(String userName, String passWord) {

//        构造查询条件
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TbUser::getUsername,userName);
//      根据用户民查询用户
        TbUser tbUser = this.getOne(queryWrapper);
        if(tbUser == null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
//        比对用户输入的内容和加密串是否一致
        if(!encoder.matches(passWord,tbUser.getPassword())){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        return BeanHelper.copyProperties(tbUser,UserDTO.class);
    }
}
